package main

import (
	"errors"
	"fmt"
	"os"
	"strings"
)

type pdfiumError struct {
	originalError error
}

func newPdfiumError(err error) *pdfiumError {
	return &pdfiumError{
		originalError: err,
	}
}

func (e *pdfiumError) Error() string {
	return e.originalError.Error()
}

// ExitCodeError представляет собой ошибку, имеющую код выхода.
type ExitCodeError struct {
	originalError error
	exitCode      int
}

func (e *ExitCodeError) Error() string {
	return e.originalError.Error()
}

// ExitCode возвращает код выхода из перечисления ExitCodeError.
func (e *ExitCodeError) ExitCode() int {
	return e.exitCode
}

func errHandler(err error, defaultCode int) {
	fmt.Print(err)

	errorCode := defaultCode

	exitCodeError := &ExitCodeError{}
	if errors.As(err, &exitCodeError) {
		errorCode = exitCodeError.ExitCode()
	}

	target := &pdfiumError{}
	if errors.As(err, &target) {
		errorMsg := target.Error()
		if strings.HasPrefix(errorMsg, "1: ") {
			errorCode = ExitCodePdfiumUnknownError
		} else if strings.HasPrefix(errorMsg, "2: ") {
			errorCode = ExitCodePdfiumFileError
		} else if strings.HasPrefix(errorMsg, "3: ") {
			errorCode = ExitCodePdfiumBadFileError
		} else if strings.HasPrefix(errorMsg, "4: ") {
			errorCode = ExitCodePdfiumPasswordError
		} else if strings.HasPrefix(errorMsg, "5: ") {
			errorCode = ExitCodePdfiumSecurityError
		} else if strings.HasPrefix(errorMsg, "6: ") {
			errorCode = ExitCodePdfiumPageError
		}
	}

	os.Exit(errorCode)
}
